package it.lupo.repository.dao;

 
import it.lupo.model.BarCode;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BarCodeDAO extends BaseDAO<BarCode, String>{

	private static Logger log = LoggerFactory.getLogger(BarCodeDAO.class);
	public final static String BARCODE = "barcode";
	public final static String CF = "CF";
	public final static String ADDRESS = "address";  
	public final static String EMAIL = "email";  
	public final static String SURNAME = "surname";
	public final static String NAME = "name";
	public final static String ID = "id";
	public BarCodeDAO()
	{
		super(BarCode.class);
	}

	public BarCode findByBarCode(String code) {
		Criteria criteria = getSession().createCriteria(BarCode.class);
		criteria.add(Restrictions.eq(BARCODE, code));
		List<BarCode> list = criteria.list();
		if(list.isEmpty())
			return null;
		return list.get(0);
	}
	
	public List<BarCode> findLasts(int limit)
	{
		Criteria criteria = getSession().createCriteria(BarCode.class);
		criteria.addOrder(Order.desc(ID));
		criteria.setFirstResult(0);
		criteria.setMaxResults(limit);
		return criteria.list();
	}
	
	public List<BarCode> search(
			String barcode,
			String cf,
			String address,
			String email,
			String name,
			String surname
		)
	{
		Criteria criteria = getSession().createCriteria(BarCode.class);
		if(barcode!=null)
			criteria.add(Restrictions.eq(BARCODE, barcode));
		if(cf!=null)
			criteria.add(Restrictions.eq(CF, cf));
		if(address!=null)
			criteria.add(Restrictions.like(ADDRESS, "%"+address+"%"));
		if(email!=null)
			criteria.add(Restrictions.like(EMAIL, "%"+email+"%"));
		if(name!=null)
			criteria.add(Restrictions.like(NAME, "%"+name+"%"));
		if(surname!=null)
			criteria.add(Restrictions.like(SURNAME, "%"+surname+"%"));
		
		
		return criteria.list();
	}

	
	
}
